//
//  RMMPersonNextViewController.m
//  Romomo
//
//  Created by puman on 2016/10/19.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMPersonNextViewController.h"
#import "RMMChangeNameView.h"
#import "RMMEditorTableViewCell.h"
#import "RMMSetPasswordView.h"
#import "RMMPersonBandDingViewController.h"
#import "RMMXiuGaiPasswordView.h"

@interface RMMPersonNextViewController ()<UITextFieldDelegate,UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMPersonNextViewController
{
    RMMChangeNameView *_changeNameView;
    RMMSetPasswordView *_passwordView;
    RMMXiuGaiPasswordView *_xiuGaiView;
    UIBarButtonItem *_item;
    UITableView *_tableView;
    NSArray *_array;
    NSArray *_nameArray;
    NSMutableArray *_dataArray;
    NSInteger _count;
    BOOL _isCanClick;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kCColor;
    self.navigationItem.title = _titleName;
    _isCanClick = NO;
    [self addViews];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    [self addRightItem];
    if ([_titleName isEqualToString:@"修改昵称"]) {
        [self changeName];
        _item.title = @"保存";
    } else if ([_titleName isEqualToString:@"绑定账号"]) {
        [self bandDing];
    } else if ([_titleName isEqualToString:@"设置登录密码"]){
        _item.title = @"完成";
        [self setPassword];
    } else {
        _item.title = @"保存";
        [self xiuGaiPassword];
    }
}
// 绑定账号
- (void)bandDing{
    _dataArray = [NSMutableArray array];
    if ([_dataDic[@"LOGIN_TYPE"] isEqualToNumber:@0]) {
        _array = @[@"微信",@"QQ"];
        _nameArray = @[@"6@3x",@"5@3x"];
        _count = 2;
        NSString *qq = [RMMFileManager retrunObjWith:_dataDic[@"QQ"]];
        NSString *wetch = [RMMFileManager retrunObjWith:_dataDic[@"WECHAT"]];
        if ([qq isEqualToString:@""]) {
            qq = @"绑定";
        }
        if ([wetch isEqualToString:@""]) {
            wetch = @"绑定";
        }
        [_dataArray addObject:wetch];
        [_dataArray addObject:qq];
    } else {
        _array = @[@"手机号码"];
        _nameArray = @[@"4@3x"];
        _count = 1;
        NSString *cust_id = [RMMFileManager retrunObjWith:_dataDic[@"CUST_ID"]];
        if (![cust_id isEqualToString:@"0"]) {
            [_dataArray addObject:[RMMFileManager retrunObjWith:_dataDic[@"LO_MOBILE"]]];
        } else {
            [_dataArray addObject:@"绑定"];
        }
        
    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 16, kScreenWideth, 54 * _count) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[RMMEditorTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, _tableView.bottom + 12, kScreenWideth - 30, 40)];
    label.font = kFont(13);
    label.numberOfLines = 0;
    label.textColor = COLORFROMCODE(0x9B9B9B, 1);
    label.text = @"为账号安全,请绑定至少一个账户。可以通过绑定的账号登录容么么";
    [self.view addSubview:label];

}
// 设置密码
- (void)setPassword{
    _passwordView = [[RMMSetPasswordView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _passwordView.password.delegate = self;
    _passwordView.passwordAgin.delegate = self;
    TEXTFIELD_S(_passwordView.password, passwordChanged:);
    TEXTFIELD_S(_passwordView.passwordAgin, passwordChanged:);
    [self.view addSubview:_passwordView];
}
- (void)addRightItem{
    _item = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:(UIBarButtonItemStylePlain) target:self action:@selector(save)];
    _item.tintColor = kWhiteColor;
}
- (void)save{
    if ([_titleName isEqualToString:@"设置登录密码"]) {
        if (_passwordView.password.text.length == 0 || _passwordView.passwordAgin.text.length == 0) {
            [RMMFileManager MBProgressWith:@"请填写完整!" onView:self.view];
            return;
        }
        if (![_passwordView.passwordAgin.text isEqualToString:_passwordView.password.text]) {
            [RMMFileManager MBProgressWith:@"两次密码输入不同!" onView:self.view];
            return;
        }
        if (_passwordView.passwordAgin.text.length < 6 || _passwordView.passwordAgin.text.length > 20) {
            [RMMFileManager MBProgressWith:@"密码输入长度有误!" onView:self.view];
            return;
        }
        
        [self setPasswordWith:@"" newPassword:_passwordView.password.text];
    } else if ([_titleName isEqualToString:@"修改密码"]) {
        if (_xiuGaiView.oldPassword.text.length == 0 || _xiuGaiView.nePassword.text.length == 0 || _xiuGaiView.againPassword.text.length == 0) {
            [RMMFileManager MBProgressWith:@"请填写完整!" onView:self.view];
            return;
        }
        if (![_xiuGaiView.nePassword.text isEqualToString:_xiuGaiView.againPassword.text]) {
            [RMMFileManager MBProgressWith:@"两次密码输入不同!" onView:self.view];
            return;
        }
        [self setPasswordWith:_xiuGaiView.oldPassword.text newPassword:_xiuGaiView.nePassword.text];
    } else if ([_titleName isEqualToString:@"修改昵称"]) {
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        parDic[@"org_no"] = Org_no;
        parDic[@"cust_id"] = [RMMFileManager shareHandle].userDic[@"CUST_ID"];
        parDic[@"name"] = _changeNameView.nameT.text;
        parDic[@"birthday"] = @"";
        parDic[@"province"] = @"";
        parDic[@"city"] = @"";
        parDic[@"gender"] = @"";
        NSString *url = UpdataCustUrl;
        [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
            NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [MMProgressHUD show];
                [MMProgressHUD dismissWithSuccess:@"修改成功!" title:nil afterDelay:1.0];
                _passwordBlcok(_changeNameView.nameT.text);
                NS_POST(@"UPDATEMINEDATA", nil, nil);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            } else {
                [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
            }
        } error:^(NSError *errors) {
            
        } view:self.view];
    }
}

// 设置密码
- (void)setPasswordWith:(NSString *)oldPassword newPassword:(NSString *)newPassword{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"newpass"] = newPassword;
    parDic[@"oldpass"] = oldPassword;
    NSString *url = SetPassword;
    [OSRequestManager requestFWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithSuccess:@"成功!" title:nil afterDelay:1];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _passwordBlcok(@"");
            [self.navigationController popViewControllerAnimated:YES];
        });
    } error:^(NSError *errors) {
        
    } view:self.view];

}
// 修改密码
- (void)xiuGaiPassword{
    _xiuGaiView = [[RMMXiuGaiPasswordView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _xiuGaiView.oldPassword.delegate = self;
    _xiuGaiView.nePassword.delegate = self;
    _xiuGaiView.againPassword.delegate = self;
    TEXTFIELD_S(_xiuGaiView.oldPassword, passwordXiuGai:);
    TEXTFIELD_S(_xiuGaiView.nePassword, passwordXiuGai:);
    TEXTFIELD_S(_xiuGaiView.againPassword, passwordXiuGai:);
    [self.view addSubview:_xiuGaiView];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 54;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RMMEditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.imageV.image = [UIImage imageNamed:_nameArray[indexPath.row]];
    cell.rightLabel.text = _dataArray[indexPath.row];
    cell.separatorInset = UIEdgeInsetsZero;

    if ([cell.rightLabel.text isEqualToString:@"绑定"]) {
        cell.rightLabel.textColor = COLORFROMCODE(0x9B9B9B, 1);
    } else {
        cell.rightLabel.textColor = kBasicColor;
        cell.rightLabel.text = [cell.rightLabel.text stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RMMPersonBandDingViewController *VC = [[RMMPersonBandDingViewController alloc] init];
    if (_count == 1) {
        VC.titleName = @"绑定手机号";
    } else {
        if (indexPath.row == 0) {
            VC.titleName = @"绑定微信";
            VC.codes = [RMMFileManager retrunObjWith:_dataDic[@"WECHAT"]];
        } else {
            VC.titleName = @"绑定QQ";
            VC.codes = [RMMFileManager retrunObjWith:_dataDic[@"QQ"]];
        }
    }
    VC.blocks = ^void(NSString *string, NSString *cust_id) {
        string = [string stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        [_dataArray replaceObjectAtIndex:indexPath.row withObject:string];
        [_tableView reloadData];
    };
    NSString *string = _dataArray[indexPath.row];
    if ([string isEqualToString:@"绑定"]) {
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        [self addAlertControllerWith:VC];
    }
}
- (void)addAlertControllerWith:(UIViewController *)VC{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定更换绑定" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *actionA = [UIAlertAction actionWithTitle:@"更换" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController pushViewController:VC animated:YES];
    }];
    UIAlertAction *actionB = [UIAlertAction actionWithTitle:@"不更换" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:actionA];
    [alertController addAction:actionB];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 改名字
- (void)changeName{
    _changeNameView = [[RMMChangeNameView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _changeNameView.nameT.delegate = self;
    _changeNameView.nameT.text = _name;
    [_changeNameView.nameT addTarget:self action:@selector(textFieldChang:) forControlEvents:(UIControlEventEditingChanged)];
    [self.view addSubview:_changeNameView];
}
- (void)textFieldChang:(UITextField *)text{
    if (text == _changeNameView.nameT) {
        if (![_name isEqualToString:text.text] && text.text.length != 0) {
            self.navigationItem.rightBarButtonItem = _item;
        } else {
            self.navigationItem.rightBarButtonItem = nil;
        }
    }
}
- (void)passwordChanged:(UITextField *)textF{
    if (_passwordView.password.text.length != 0 && _passwordView.passwordAgin.text.length != 0) {
        self.navigationItem.rightBarButtonItem = _item;
    } else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}
- (void)passwordXiuGai:(UITextField *)textF{
    if (_xiuGaiView.oldPassword.text.length != 0 && _xiuGaiView.nePassword.text.length != 0 && _xiuGaiView.againPassword.text.length != 0) {
        self.navigationItem.rightBarButtonItem = _item;
    } else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
